"""
会话管理模块
"""
import os
import sys
import time
from typing import Dict, List, Optional
from datetime import datetime, timedelta
import threading

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config import SYSTEM_CONFIG
from utils.logger import setup_logger

logger = setup_logger(__name__)

class Session:
    def __init__(self, session_id: str):
        """
        初始化会话
        
        Args:
            session_id: 会话ID
        """
        self.session_id = session_id
        self.last_active = datetime.now()
        self.history = []
        self.max_history_len = SYSTEM_CONFIG['max_history_len']
        
    def add_interaction(self, question: str, answer: str, context: List[Dict] = None):
        """
        添加一次交互记录
        
        Args:
            question: 用户问题
            answer: 系统回答
            context: 相关文档上下文
        """
        self.history.append({
            'timestamp': datetime.now(),
            'question': question,
            'answer': answer,
            'context': context
        })
        self.last_active = datetime.now()
        
        # 保持历史记录在限定长度内
        if len(self.history) > self.max_history_len:
            self.history = self.history[-self.max_history_len:]
    
    def get_recent_context(self, num_turns: int = 3) -> str:
        """
        获取最近的对话历史
        
        Args:
            num_turns: 获取的对话轮数
        
        Returns:
            str: 格式化的对话历史
        """
        if not self.history:
            return "无历史对话"
            
        context = []
        for interaction in self.history[-num_turns:]:  # 只取最近num_turns次对话
            context.extend([
                f"用户: {interaction['question']}",
                f"助手: {interaction['answer']}\n"
            ])
        return "\n".join(context)
    
    def is_expired(self) -> bool:
        """
        检查会话是否过期
        
        Returns:
            bool: 是否过期
        """
        expire_minutes = SYSTEM_CONFIG['session_expire_minutes']
        return datetime.now() - self.last_active > timedelta(minutes=expire_minutes)

class SessionManager:
    def __init__(self):
        """初始化会话管理器"""
        self.sessions: Dict[str, Session] = {}
        self.lock = threading.Lock()
        
        # 启动清理线程
        self.cleanup_thread = threading.Thread(target=self._cleanup_expired_sessions, daemon=True)
        self.cleanup_thread.start()
    
    def get_session(self, session_id: str) -> Session:
        """
        获取或创建会话
        
        Args:
            session_id: 会话ID
            
        Returns:
            Session: 会话对象
        """
        with self.lock:
            if session_id not in self.sessions:
                self.sessions[session_id] = Session(session_id)
            return self.sessions[session_id]
    
    def remove_session(self, session_id: str):
        """
        移除会话
        
        Args:
            session_id: 会话ID
        """
        with self.lock:
            if session_id in self.sessions:
                del self.sessions[session_id]
    
    def get_all_sessions(self) -> Dict[str, Session]:
        """获取所有活跃会话"""
        with self.lock:
            return self.sessions
    
    def _cleanup_expired_sessions(self):
        """清理过期会话的后台任务"""
        while True:
            time.sleep(SYSTEM_CONFIG['session_cleanup_interval'].total_seconds())
            try:
                with self.lock:
                    current_time = datetime.now()
                    expired_sessions = [
                        session_id for session_id, session in self.sessions.items()
                        if session.is_expired()
                    ]
                    
                    for session_id in expired_sessions:
                        logger.info(f"清理过期会话: {session_id}")
                        del self.sessions[session_id]
                        
            except Exception as e:
                logger.error(f"清理过期会话时出错: {str(e)}")
